const env = require('./config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;

const base64 = require('./base64.js'); //Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 */
const uploadFile = function(filePath, fn) {
	if (!filePath || filePath.length < 9) {
		uni.showModal({
			title: '路径错误',
			content: '请重试',
			showCancel: false,
		})
		return;
	}
	let extName = filePath.split('.')[filePath.split('.').length - 1]
	let fileKey = env.dirPath + new Date().getTime() + Math.floor(Math.random() * 1500) + '.' + extName;

	const serverURL = env.uploadUrl; //OSS地址，需要https
	const accessid = env.OSSAccessKeyId;
	const policyBase64 = getPolicyBase64();
	const signature = getSignature(policyBase64); //获取签名
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: serverURL,
			filePath: filePath,
			name: 'file',
			formData: {
				key: fileKey,
				policy: policyBase64,
				OSSAccessKeyId: accessid,
				signature: signature,
				success_action_status: 200,
			},
			success(res) {
				if (res.statusCode != 200) {
					reject(new Error('上传错误:' + JSON.stringify(res)))
					return;
				}
				resolve(env.Url + fileKey);
			},
			fail(err) {
				err.wxaddinfo = serverURL;
				reject(err);
			},
		})

		uploadTask.onProgressUpdate((res) => {
			fn(res.progress)
			// uni.$emit('upload_progress', {
			// 	progress: res.progress
			// })
		});
	})

}

const getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
		"conditions": [
			["content-length-range", 0, 800 * 1024 * 1024] // 设置上传文件的大小限制,800mb
		]
	};

	const policyBase64 = base64.encode(JSON.stringify(policyText));
	return policyBase64;
}

const getSignature = function(policyBase64) {
	const accesskey = env.AccessKeySecret;

	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	return signature;
}

module.exports = uploadFile;